package pers.hl.module_main.book_detail

import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import pers.hl.common.base.BaseVBVMActivity
import pers.hl.common.base.ext.showMessage
import pers.hl.common.utils.UiUtils
import pers.hl.lib_global.common.GlideUtils
import pers.hl.lib_global.model.bean.Book
import pers.hl.lib_global.model.bean.Comment
import pers.hl.lib_global.model.bean.Reply
import pers.hl.module_main.R
import pers.hl.module_main.admin.book.BookManageViewModel
import pers.hl.module_main.book_detail.DetailItem.Companion.TYPE_EMPTY
import pers.hl.module_main.common.CommonDialog
import pers.hl.module_main.common.PageHelper
import pers.hl.module_main.databinding.ActivityBookDetailBinding
import pers.hl.module_main.databinding.ItemRvCommentBinding

class BookDetailActivity : BaseVBVMActivity<ActivityBookDetailBinding, BookManageViewModel>() {

    private lateinit var mBook: Book
    private lateinit var detailAdapter: DetailAdapter

    companion object {
        const val KEY_DATA_BOOK = "key_data_book"
    }

    override fun initView(savedInstanceState: Bundle?) {
        initTitle()
        initRv()
        blurBackground()
        fillBaseInfo()
    }

    private fun initTitle() {
        mBinding.titleBar.apply {
            tvBarTitle.text = "图书详情"
            ivBarLeft.setOnClickListener {
                finish()
            }
            ivBarRight.setOnClickListener {
                if (ivBarRight.visibility != View.VISIBLE) {
                    return@setOnClickListener
                }
                collectBook(mBook)
            }
        }
    }

    private fun initRv() {
        mBinding.apply {
            rvDetail.layoutManager = LinearLayoutManager(this@BookDetailActivity)
            detailAdapter = DetailAdapter(this@BookDetailActivity)
            rvDetail.adapter = detailAdapter
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        fetchBookInfo()
    }

    private fun fetchBookInfo() {
        mBook.bookId?.let { bookId ->
            mViewModel.fetchBookInfo(bookId).observe(this, Observer {
                mBook = it
                detailAdapter.setList(emptyList())
                setCollectIcon(mBook)
                fillBaseInfo()
                fetchComments()
            })
        }
    }

    private fun setCollectIcon(book: Book) {
        mBinding.titleBar.ivBarRight.setImageResource(if (book.isCollect()) R.drawable.ic_collect_fill else R.drawable.ic_collect)
    }

    private fun fetchComments() {
        mBook.bookId?.let {
            mViewModel.fetchComments(it).observe(this, Observer { list ->
                if (list.isNotEmpty()) {
                    detailAdapter.addData(list)
                } else {
                    showEmptyCommentView()
                }
            })
        }
    }

    private fun showEmptyCommentView() {
        val emptyCommentText =
            DetailItem.DetailText(DetailItem.Text(DetailItem.TYPE_COMMENT, "暂无评论数据，点击添加"))
        detailAdapter.addData(emptyCommentText)
    }

    private fun blurBackground() {
        GlideUtils.fetchBitmap(this, mBook.bookImg.toString()) {
            LogUtils.d("fetchBitmap success，start rsBlur")
            val bitmap = UiUtils.rsBlur(this, it, 25, 1f / 8f)
            mBinding.root.background = BitmapDrawable(resources, bitmap)
        }

    }

    override fun initParams() {
        intent?.apply {
            mBook = intent.getParcelableExtra(KEY_DATA_BOOK)
        }
    }

    private fun fillBaseInfo() {
        initHeaderData()
        initBelowData()
    }

    private fun initBelowData() {
        // 描述标题
        val descTitleData = DetailItem.DetailTitle(DetailItem.Title(DetailItem.TYPE_DESC, "简介"))
        detailAdapter.remove(descTitleData)
        detailAdapter.addData(descTitleData)

        // 描述数据
        if (TextUtils.isEmpty(mBook.bookDesc)) {
            val descEmptyData = DetailItem.DetailText(DetailItem.Text(TYPE_EMPTY, "暂无数据"))
            detailAdapter.remove(descEmptyData)
            detailAdapter.addData(descEmptyData)
        } else {
            val descData =
                DetailItem.DetailText(DetailItem.Text(DetailItem.TYPE_DESC, mBook.bookDesc))
            detailAdapter.remove(descData)
            detailAdapter.addData(descData)
        }

        // 评论标题
        val commentTitleData =
            DetailItem.DetailTitle(DetailItem.Title(DetailItem.TYPE_COMMENT, "评论"))
        detailAdapter.remove(commentTitleData)
        detailAdapter.addData(commentTitleData)

    }
    private fun initHeaderData() {
        if (detailAdapter.hasHeaderLayout()) {
            detailAdapter.removeAllHeaderView()
        }
        val headerData = DetailItem.DetailHeader(mBook)
        detailAdapter.addData(headerData)
    }

    fun addComment(comment: String) {
        mBook.bookId?.let {
            mViewModel.addComment(it, comment).observe(this, Observer {
                showMessage("评论成功")
                fetchBookInfo()
            })
        }
    }

    fun deleteComment(comment: Comment) {
        val id = comment.cmtId ?: return
        mViewModel.deleteComment(id).observe(this, Observer {
            showMessage("删除成功")
            fetchBookInfo()
        })
    }

    fun addReply(cmtId: Int?, replyContent: String) {
        cmtId?.let {
            mViewModel.addReply(it, replyContent).observe(this, Observer {
                fetchBookInfo()
            })
        }
    }

    fun fetchReplyList(comment: Comment) {
        comment.cmtId?.let {
            mViewModel.fetchReplyList(it).observe(this, Observer { list ->
                if (list == null || list.isEmpty()) {
                    showMessage("暂无回复")
                    return@Observer
                }
                showReplyListDialog(list)
            })
        }

    }

    /**
     * 查看回复列表弹框
     */
    private fun showReplyListDialog(list: List<Reply>) {
        CommonDialog.createBottomList(
            mContext,
            list.toMutableList(),
            R.layout.item_rv_comment,
            convertBlock = { holder, item ->
                val binding = ItemRvCommentBinding.bind(holder.itemView)
                binding.apply {
                    item.rplUserId?.let {
                        GlideUtils.loadUserAvatar(
                            mContext, binding.ivAvatar,
                            it, R.drawable.ic_personal_center
                        )
                    }
                    tvCommenter.text =
                        if (TextUtils.isEmpty(item.rplUserName)) "匿名用户" else item.rplUserName
                    tvTime.text = TimeUtils.date2String(item.rplTime)
                    tvComment.text = item.rplInfo
                    ivAvatar.setOnClickListener {
                        PageHelper.startUserHomePage(mContext, item.rplUserId)
                    }
                }
            },
            onItemClick = { layer, adapter, position, item ->
                LogUtils.d("点击回复")
            }).show()
    }

    /**
     * 取消/收藏书籍
     */
    fun collectBook(data: Book) {
        if (data.isCollect()) {
            data.bookId?.let {
                mViewModel.unCollect(it).observe(this, Observer {
                    showMessage("取消收藏成功")
                    data.collect = 0
                    val headerData = DetailItem.DetailHeader(data)
                    detailAdapter.setData(0, headerData)
                    setCollectIcon(data)
                })
            }
        } else {
            data.bookId?.let {
                mViewModel.collect(it).observe(this, Observer {
                    showMessage("收藏成功")
                    data.collect = 1
                    val headerData = DetailItem.DetailHeader(data)
                    detailAdapter.setData(0, headerData)
                    setCollectIcon(data)
                })
            }
        }
    }

    fun borrowBook(data: Book) {
        data.bookId?.let {
            mViewModel.borrow(it).observe(this, Observer {
                showMessage("请求借阅成功，请到我的借阅页面查看详情")
                fetchBookInfo()
            })
        }
    }


}